<template>
  <div class="goods-show">
      <div class="goods-img">
        <van-icon name="arrow-left" class="goods-callback" @click.native="callback" />
        <img :src="listdata.imgsrc" alt="">
      </div>
      <div>
        <van-panel :title="listdata.name" :desc="listdata.describe" :status="'￥'+listdata.price">
          <van-tabs v-model="active">
            <van-tab title="商品详情">商品详情</van-tab>
            <van-tab title="评价">评价</van-tab>
            <van-tab title="同款推荐">{{shopCar}}</van-tab>
          </van-tabs>
        </van-panel>
      </div>
      <div>
        <van-goods-action>
          <van-goods-action-mini-btn
            icon="chat-o"
            text="客服"
          />
          <van-goods-action-mini-btn 
            icon="cart-o"
            text="购物车"
            to="/shopcar"
            :info="shopCar.length"
          />
          <van-goods-action-big-btn
            text="加入购物车"
            @click.native="addShopCar(listdata.id)"
          />
          <van-goods-action-big-btn
            primary
            text="立即购买"
          />
        </van-goods-action>
      </div>
    </div>
</template>
<script>
// 引入vuex
import { mapState, mapMutations } from 'vuex'
export default {
  data () {
    return {
      id: '',
      fid: '',
      active: 0,
      listdata: []
    }
  },
  mounted () {
    var _this = this
    _this.id = this.$route.query.id
    _this.fid = this.$route.query.fid
    // 遍历对象要用for in 来遍历
    // 将符合条件的商品写入listdata数组
    for (var i in this.goods) {
      if (this.goods[i].id == _this.fid) {
        for (var j in this.goods[i].sclass) {
          if (this.goods[i].sclass[j].id == _this.id) {
            this.listdata = this.goods[i].sclass[j]
          }
        }
      }
    }
  },
  methods: {
    ...mapMutations(['addshopCar','addshopCarNum']),
    callback () {
      window.history.go(-1)
    },
    addShopCar (id) {
      // 循环已有的shopCar数组
      for(var i in this.shopCar){
        // 判断当前商品是否已存在购物车
        if(this.shopCar[i].id == id){
          // 如果存在调用addshopCarNum 并传入id
          this.$store.commit('addshopCarNum',id)
          return 
        }
      }
      // 点击加入购物车
      this.$store.commit('addshopCar',this.listdata)
      // 跳转到购物车页面
       this.$router.push({path: '/Shopcar'})
    }
  },
  computed: {
    ...mapState(['goods','shopCar'])
  }
}
</script>

<style scoped>
/* 商品展示 */
.goods-show{
  width: 100%;
  height: 100%;
  z-index:999;
  position: absolute;
  top: 0;
  background: #fff;
}
.goods-img img{
  width: 100%;
  height: 100%;
}
.goods-callback{
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 1.5em;
  color:#fff;
  background: rgba(0,0,0,0.5);
  border-radius: 50%;
  padding: 10px;
}
</style>

